/*
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-02-24 08:53:27
 * @Descripttion: 库房管理员
 */

import { Component, OnInit } from '@angular/core';
import { WarehouseManageService } from './warehouse-manage.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { resolve } from 'url';
import { HCommonService } from 'src/app/h-common/h-common.service';

@Component({
  selector: 'app-warehouseuser-manage',
  templateUrl: './warehouseuser-manage.component.html',
  styleUrls: ['./warehouseuser-manage.component.scss']
})
export class WarehouseuserManageComponent implements OnInit {

  modalDomBox : any

  power:any

  KFList = []
  KQList = []
  defaultKQList = []
  // 获取库房列表
  getKFList() {
    return new Promise((resolve, reject) => {
      try {
        this.WarehouseManageService.getKFList().subscribe(res => {
          this.KFList = res
          resolve()
        })
      } catch (e) {
        reject(e)
      }
    })
  }
  getKQList(id) {
    for (let i = 0; i < this.KFList.length; i++) {
      if (this.KFList[i].id == id) {
        this.KQList = this.KFList[i].warehouseAreas
      }
    }
  }
  getDefaultKQList(id) {
    for (let i = 0; i < this.KFList.length; i++) {
      if (this.KFList[i].id == id) {
        this.defaultKQList = this.KFList[i].warehouseAreas
      }
    }
  }

  // table1 start
  currentManagePage: any = '1';
  pageIndexManage: any = '0';
  pageSize: string = '10';
  totalSizeManage: any = '';
  listOfData = [];
  selectedManage: string = '';
  // 获取管理员列表
  async getManagerList() {
    let dataJson = {
      page: this.pageIndexManage,
      size: this.pageSize
    }
    let list: any = await this.WarehouseManageService.getManagerList(dataJson)
    this.listOfData = list.content
    this.totalSizeManage = list.totalElements
  }
  selectMange(id) {
    this.mapOfCheckedIdDetail = {}
    this.numberOfCheckedDetail = 0
    this.deleteManageCk = []
    this.getMangeCKList(id)
  }
  // 点击页码
  clickPageMange(pageIndex) {
    this.currentManagePage = pageIndex
    this.pageIndexManage = pageIndex - 1
    this.getManagerList()
  }
  // table1 end

  // table2 start
  isCanAddEdit: boolean = true;
  listOfDataDetail = [];
  listOfDisplayDataDetail = [];
  isAllDisplayDataCheckedDetail = false;
  isIndeterminateDetail = false;
  mapOfCheckedIdDetail: { [key: string]: boolean } = {};
  numberOfCheckedDetail = 0;
  currentManageCKPage: any = '1';
  pageIndexManageCK: any = '0';
  totalSizeManageCK: any = '';
  deleteManageCk = []
  async getMangeCKList(id) {
    let dataJson = {
      managerId: id,
      page: this.pageIndexManageCK,
      size: this.pageSize
    }
    let list: any = await this.WarehouseManageService.getManagerCKList(dataJson)
    this.listOfDataDetail = list.content
    this.totalSizeManageCK = list.totalElements
    this.isCanAddEdit = false
    this.selectedManage = id
  }
  // 点击页码
  clickPageMangeCk(pageIndex) {
    this.currentManageCKPage = pageIndex
    this.pageIndexManageCK = pageIndex - 1
    this.getMangeCKList(this.selectedManage)
  }
  currentPageDataChangeDetail($event): void {
    this.listOfDisplayDataDetail = $event;
    this.refreshStatusDetail();
  }

  refreshStatusDetail(): void {
    this.isAllDisplayDataCheckedDetail = this.listOfDisplayDataDetail
      .filter(item => !item.disabled)
      .every(item => this.mapOfCheckedIdDetail[item.id]);
    if (this.listOfDisplayDataDetail.length == 0) {
      this.isAllDisplayDataCheckedDetail = false
    }
    this.isIndeterminateDetail =
      this.listOfDisplayDataDetail.filter(item => !item.disabled).some(item => this.mapOfCheckedIdDetail[item.id]) &&
      !this.isAllDisplayDataCheckedDetail;
    this.numberOfCheckedDetail = this.listOfDataDetail.filter(item => this.mapOfCheckedIdDetail[item.id]).length;
    // 删除库房管理员下的仓库id
    let newList = []
    let ids = Object.keys(this.mapOfCheckedIdDetail)
    for (let i = 0; i < ids.length; i++) {
      if (this.mapOfCheckedIdDetail[ids[i]]) {
        newList.push(ids[i])
      }
    }
    this.deleteManageCk = newList
  }

  checkAllDetail(value: boolean): void {
    this.listOfDisplayDataDetail.filter(item => !item.disabled).forEach(item => (this.mapOfCheckedIdDetail[item.id] = value));
    this.refreshStatusDetail();
  }

  // 删除库房管理员下的仓库
  deleteManageCK(id: any) {
    let that = this
    this.modalService.confirm({
      nzTitle: '确定要删除此条数据吗？',
      nzContent: '',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: async function () {
        that.deleteManageCk.push(id)
        let _res1: any = await that.WarehouseManageService.deleteManageCK(that.deleteManageCk)
        that.deleteManageCk = []
        that.getMangeCKList(that.selectedManage)
      },
      nzOnCancel: function () {
        that.deleteManageCk = []
      }
    });
  }
  deleteMoreManageCK() {
    let that = this
    if (this.deleteManageCk.length == 0) {
      this.message.create("error", "请选择删除条目")
    } else {
      this.modalService.confirm({
        nzTitle: '确定要删除这些数据吗？',
        nzContent: '',
        nzOkText: '确认',
        nzCancelText: '取消',
        nzOnOk: async function () {
          let _res2: any = await that.WarehouseManageService.deleteManageCK(that.deleteManageCk)
          that.deleteManageCk = []
          that.mapOfCheckedIdDetail = {}
          if (that.isAllDisplayDataCheckedDetail) {
            that.pageIndexManageCK = 0
            that.currentManageCKPage = 1
          }
          that.getMangeCKList(that.selectedManage)
        }
      });
    }
  }
  // table2 end

  // detailModal start
  isVisible: boolean = false;//展示弹出框
  modalType: number = 1;
  curEditCK: string = '';
  kfIdModal: string = '';
  kqIdModal: string = '';
  defaultKFIdModal: string = '';
  defaultKQIdModal: string = '';
  isDefaultCK: boolean = false;
  editCurCK: string = ''
  ckForm: FormGroup;
  selectedKF(data) {
    this.getKQList(data)
  }
  selectDefault(data) {
    this.getDefaultKQList(data)
  }
  showModal(type): void {
    this.modalType = type
    this.isVisible = true;
    if (type == 2) {
      let data = this.listOfDataDetail.filter(item => {
        return item.id == this.deleteManageCk[0]
      })[0]
      this.editCurCK = data.id;
      this.ckForm.patchValue({
        kfIdModal: data.warehouseId,
        kqIdModal: data.warehouseAreaId,
        defaultKFIdModal: data.toWarehouseId,
        defaultKQIdModal: data.toWarehouseAreaId,
        isDefaultCK: data.isDefault
      })
    } else {
      this.ckForm.reset()
    }
  }

  handleCancel(): void {
    this.isVisible = false;
  }
  // 新增修改管理员下的仓库
  submitck() {
    for (const i in this.ckForm.controls) {
      this.ckForm.controls[i].markAsDirty();
      this.ckForm.controls[i].updateValueAndValidity();
    }
    if (this.ckForm.status == 'VALID') {
      let _value = this.ckForm.value;
      this.addEditManageCk(_value)
    }
  }
  async addEditManageCk(data) {
    let dataJson = {
      managerId: this.selectedManage,
      toWarehouseAreaId: data.defaultKQIdModal?data.defaultKQIdModal:'',
      toWarehouseId: data.defaultKFIdModal?data.defaultKFIdModal:'',
      warehouseAreaId: data.kqIdModal?data.kqIdModal:'',
      warehouseId: data.kfIdModal?data.kfIdModal:'',
      isDefault: data.isDefaultCK?data.isDefaultCK:false
    }
    let dataJson1 = {
      id: this.editCurCK,
      managerId: this.selectedManage,
      toWarehouseAreaId: data.defaultKQIdModal?data.defaultKQIdModal:'',
      toWarehouseId: data.defaultKFIdModal?data.defaultKFIdModal:'',
      warehouseAreaId: data.kqIdModal?data.kqIdModal:'',
      warehouseId: data.kfIdModal?data.kfIdModal:'',
      isDefault: data.isDefaultCK?data.isDefaultCK:false
    }
    if (this.modalType == 1) {
      let _res1: any = await this.WarehouseManageService.addManagerCKList(dataJson)
    } else if (this.modalType == 2) {
      let _res2: any = await this.WarehouseManageService.editManagerCKList(dataJson1)
    }
    this.getMangeCKList(this.selectedManage)
    this.isVisible = false;
  }
  // detailModal end

  constructor(
    private message: NzMessageService,
    private modalService: NzModalService,
    private WarehouseManageService: WarehouseManageService,
    private CKForm: FormBuilder,
    private HCommonService: HCommonService
  ) { }

  ngOnInit() {
    this.modalDomBox = document.querySelector("#modal_box");
    /* 获取权限 */
    this.power = this.HCommonService.getRoles("warehouseManager");

    this.getManagerList()
    this.getKFList()

    this.ckForm = this.CKForm.group({
      kfIdModal: ['', [Validators.required]],
      kqIdModal: [''],
      defaultKFIdModal: [''],
      defaultKQIdModal: [''],
      isDefaultCK: [false]
    })
  }

}
